<!-- 获取当地天气 -->
<template>
    <div class="flex-center">
        <!--获取天气情况-->
        <div v-for="item in weather" :key="item" class="flex-center font-22"></div>
        <skycon v-if="iconCondition" :condition="iconCondition" color="powderblue" size="40" />
<!--      <span>省份：{{weather.province}}</span>-->
<!--      <span>城市：{{weather.city}}</span>-->
        <div id="line" class="echart-line" style="min-width: calc(100vw - 250px);height:600px;"></div>

      <!-- 轮播图展示天气情况-->
    </div>
</template>


<script>
import axios from 'axios';
import Skycon from 'vue-skycons';
import * as echarts from 'echarts';
const option={
      title: {
        text: '天气变化折线图',
        subtext:'',
        textStyle:{
          fontSize:30,
        },
        // top:'bottom',
        left:'left'

      },
      grid: {
        left: '10%',
        bottom: '10%',
        top: '10%',
        right: '10%'
      },
      tooltip: {
        trigger: 'axis', //坐标轴触发器,主要在柱状图,折线图等类目轴的图表中使用
        axisPointer:{
          type:'cross',
          axis:'auto',
          snap:true,//坐标轴指示器自动吸附到点上
        },
        showContent:true,
        textStyle:{
          fontSize: 20,
        }
      },
      color:["#f60","#50ead4"],
      legend: {
        textStyle:{
          fontSize:25,
          fontWeight:40,
        }
      },
      toolbox: {
        show: true,
        feature: {
          // dataZoom: {
          //   yAxisIndex: 'none'
          // },
          dataView: { readOnly: false },
          magicType: { type: ['line', 'bar'] },
          restore: {},
          saveAsImage: {}
        }
      },
      //x坐标轴
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [], //从后台动态获取
        axisLabel:{
          textStyle:{
            fontSize: 20,
          },
          lineStyle:{
            width:5
          }
        }
      },
      //y坐标轴
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} °C',
          textStyle:{
            fontSize: 20,
          },
          lineStyle:{
            width:5
          }
        },

      },
      series: [
        {
          name: '白天气温',
          type: 'line',
          data: [],
          lineStyle:{
            normal:{
              color: "#f60",
            }
          },
          markPoint: {
            data: [
              { type: 'max', name: '白天最高温' },
              { type: 'min', name: '白天最低温' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          },
          label:{
            show:true,
            position:'top'
          }
        },
        {
          name: '夜晚气温',
          type: 'line',
          data: [],
          lineStyle:{
            normal:{
              color: "#50ead4",
            }
          },
          markPoint: {
            data: [
                { name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 },
                { type: 'max', name: '夜间最高温' },
                { type: 'min', name: '夜间最低温' }]
          },
          markLine: {
            data: [
              { type: 'average', name: 'Avg' },
              [
                {
                  symbol: 'none',
                  x: '90%',
                  // yAxis: 'max'
                },
                {
                  symbol: 'circle',
                  label: {
                    position: 'start',
                    formatter: 'Max'
                  },
                  type: 'max',
                  name: '最高点'
                }
              ]
            ]
          },
          label:{
                show:true,
                position:'top'
          }
        },
        // {name:'日期',type:'bar',data:[]},
      ]
    };
// const legend = {data:['白天气温','夜晚气温','风向','天气']}
export default {
  name:'LocalWeather',
  components: { Skycon },
  data() {
    return {
      key: '1a908afe2b54a3f904c5d0aa419343c7', //自己的key
      weather: {}, //用于存放天气相关的数据
      iconCondition: null, //icon值
      lineBox:null,//初始化作用
      adcode:"330100", //杭州的adcode
    };
  },
  created() {
    this.getLocationInfo();
  },
  mounted() {
    this.load()
  },
  methods: {
    load(){
      this.getLocationInfo()
      // this.setWeatherIcon(this.weather)
    },
    // 获取用户位置信息
    async getLocationInfo() {
      const params = {
        key: this.key,
      };
      const { data } = await axios.get('https://restapi.amap.com/v3/ip', { params });
      // data.adcode值为获取天气需要的city值
      this.getWeather(data.adcode);
    },
    // 获取天气详情
    async getWeather(adcode) {
      const params = {
        key: this.key,
        city: adcode,
        extensions:"all"
      };

      const { data } = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo`, { params });
      // this.weather = data.lives[0];
      this.weather=data.forecasts[0] //获取整个字段
      // console.log("天气状况是",this.weather)
      const daysList=this.weather.casts
      this.iconCondition = this.setWeatherIcon(data.forecasts[0]?.casts[0].dayweather); //获取当日天气状况
      // console.log('data数据是',data.forecasts[0])
      option.title.subtext = '当前城市：'+this.weather.city
      if(!this.lineBox){
        this.lineBox = echarts.init(document.getElementById('line'))//初始化echarts容器
      }else {
        daysList.forEach((item) => {
          option.xAxis.data.push(item.date)
          option.series[0].data.push(item.daytemp)
          option.series[1].data.push(item.nighttemp)
        })
        // option.series[4].data.push(item.date)
        this.lineBox.setOption(option);
      }
      // console.log("daysList数据是11111111",this.weather)
      // console.log("option.xAxis.data值为",option.series[0].data)
    },
    // // 设置icon
    setWeatherIcon(weather) {
      // 只处理了基础的天气，可以继续精细化处理
      if (weather === '晴') {
        return 'clear-day';
      } else if (weather.includes('云')) {
        return 'partly-cloudy-day';
      } else if (weather.includes('风')) {
        return 'wind';
      } else if (weather.includes('雨')) {
        return 'rain';
      } else if (weather.includes('雪')) {
        return 'snow';
      } else if (weather.includes('雾')) {
        return 'fog';
      }
      return 'cloudy';
    },
  },
};
</script>
<style lang="less" scoped>
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.font-22 {
  font-size: 22px;
}
.skycon{

}
</style>